import configparser

import pandas as pd
from sqlalchemy import create_engine

# 创建 ConfigParser 对象
config = configparser.ConfigParser()

# 读取配置文件
config.read('../database_config.ini')

# 获取数据库连接配置信息

block = 'Database_test'  # 开发环境
# block = 'Database'      # 生产环境

host = config.get(block, 'host')
port = config.get(block, 'port')
username = config.get(block, 'username')
password = config.get(block, 'password')
db_name = config.get(block, 'database')

# 创建 SQLAlchemy 引擎
engine = create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{db_name}?charset=utf8')


def write_to_mysql(dataframe, table_name):
    # 将 DataFrame 写入 MySQL 表
    dataframe.to_sql(name=table_name, con=engine, if_exists='append', index=False)


def close_mysql():
    # 关闭数据库连接
    engine.dispose()


if __name__ == '__main__':
    data = {
        'username': ['小明', '小红'],
        'password': ['1111', '1345']
    }
    df = pd.DataFrame(data)
    write_to_mysql(dataframe=df, table_name='user')
